package com.zhr.tea.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;

import com.alibaba.fastjson.JSONObject;
import com.zhr.tea.R;
import com.zhr.tea.api.FenLeiApi;
import com.zhr.tea.entity.HotSearch;
import com.zhr.tea.view.adapter.HistoryAdapter;
import com.zhr.tea.view.adapter.HotSearchAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;
import okhttp3.Headers;

public class SearchActivity extends AppCompatActivity implements View.OnClickListener {
    @BindView(R.id.search_et)
    AutoCompleteTextView searchEt;
    @BindView(R.id.search_hotrecy)
    RecyclerView searchHotrecy;
    @BindView(R.id.search_history)
    RecyclerView searchHistory;
    @BindView(R.id.search_btn)
    Button searcheBtn;




    private ArrayAdapter<String> arrayAdapter;

    private List<String> searchData = new ArrayList<>();

    private List<String> hotSearchData = new ArrayList<>();

    private List<String> historyData = new ArrayList<>();

    private HotSearchAdapter hotAdapter;
    private HistoryAdapter historyAdapter;

    private String searchWord = "";

    private String searchKey = "";

    private String afterEt = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        historyData.add("暂无历史记录");
        initView();
        initData();
        addListener();
        historyAdapter.notifyDataSetChanged();
    }


    private void addListener() {
        searcheBtn.setOnClickListener(this);  //设置btn的点击事件

        /***
         * 热门搜索点击项的 点击事件
         *
         */
        hotAdapter.setOnItemClickListener(new HotSearchAdapter.RecyClickListener() {
            @Override
            public void onItemClick(String title) {
                searchWord = title;
                Intent intent = new Intent(SearchActivity.this, FenLeiActivity.class);
                intent.putExtra("title", searchWord);
                startActivity(intent);
            }
        });


        /***
         * 历史记录的点击事件
         *
         */
        historyAdapter.setOnItemClickListener(new HistoryAdapter.RecyClickListener() {
            @Override
            public void onItemClick(String tag) {
                searchWord = tag;
                if (tag.equals("清空历史记录")) {
                    historyData.clear();
                    historyData.add("暂无历史记录");
                    historyAdapter.notifyDataSetChanged();
                } else if (!tag.equals("暂无历史记录")) {
                    Intent intent = new Intent(SearchActivity.this, FenLeiActivity.class);
                    intent.putExtra("title", searchWord);
                    startActivity(intent);
                }
            }
        });

        /***
         * 自动文本框的 内容变更  监听事件
         *
         */
        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                searchKey = charSequence.toString();
                initSearch();
            }

            @Override
            public void afterTextChanged(Editable editable) {
                afterEt = editable.toString();
            }
        });

    }

    private void initSearch() {

        /*****
         * 搜索 自动文本输入时的数据加载
         *
         *
         */
        if (searchData.size() != 0) {
            searchData.clear();
        }
        RequestParams key = new RequestParams();
        key.addHeader("Content-Type", "application/json");
        JSONObject keyJson = new JSONObject();
        keyJson.put("key", searchKey);
        key.applicationJson(keyJson);

        HttpRequest.post(FenLeiApi.SEARCH_URL, key, new BaseHttpRequestCallback<String>() {
            @Override
            protected void onSuccess(Headers headers, String s) {
                super.onSuccess(headers, s);
                HotSearch search = JSONObject.parseObject(s, HotSearch.class);
                searchData.addAll(search.getContent());
                arrayAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });


    }

    private void initData() {

        /***
         * 加载 热门 搜索的数据
         */
        RequestParams params = new RequestParams();
        params.addHeader("Content-Type", "application/json");
        JSONObject json = new JSONObject();
        json.put("tagType", "hot_word");
        params.applicationJson(json);
        HttpRequest.post(FenLeiApi.HOTSEARCH_URL, params, new BaseHttpRequestCallback<String>() {
            @Override
            protected void onSuccess(String s) {
                super.onSuccess(s);
                HotSearch hot = JSONObject.parseObject(s, HotSearch.class);
                hotSearchData.addAll(hot.getContent());
                hotAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });


    }

    private void initView() {

        arrayAdapter = new ArrayAdapter<String>(SearchActivity.this, android.R.layout.simple_list_item_1, historyData);
        searchEt.setAdapter(arrayAdapter);

        hotAdapter = new HotSearchAdapter(this, hotSearchData);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        searchHotrecy.setLayoutManager(manager);
        searchHotrecy.setAdapter(hotAdapter);


        historyAdapter = new HistoryAdapter(this, historyData);
        RecyclerView.LayoutManager historymanager = new LinearLayoutManager(this);
        searchHistory.setLayoutManager(historymanager);
        searchHistory.setAdapter(historyAdapter);
    }


    /**
     * 搜索BTN 的点击事件
     *
     * @param view
     */

    @Override
    public void onClick(View view) {
        if (historyData.size() == 1) {
            historyData.clear();

            historyData.add(afterEt);
            historyData.add("清空历史记录");
        } else {
            historyData.remove(historyData.size());
            historyData.add(afterEt);
            historyData.add("清空历史记录");
        }
        historyAdapter.notifyDataSetChanged();
        Intent intent = new Intent(SearchActivity.this, FenLeiActivity.class);
        intent.putExtra("title", afterEt);
        startActivity(intent);
    }
}
